<template>
    <LayoutWrap class="permission">
        <el-form @submit.native.prevent ref="formSearch" :inline="true" :model="formSearch" label-width="90px">
            <div class="search-wrap">
                <div class="search-item" :class="{left: !isMobile}">
                    <el-form-item label="仓库" prop="depot">
                        <el-select
                            v-model="formSearch.depot"
                            filterable
                            clearable
                            placeholder="请选择"
                            style="width: 322px"
                            @keyup.enter.native="getList"
                        >
                            <el-option
                                v-for="item in optionsDepots"
                                :key="item._id"
                                :label="item.name"
                                :value="item._id"
                            >
                            </el-option>
                        </el-select>
                    </el-form-item>
                </div>

                <div class="search-item" :class="{left: !isMobile}">
                    <el-form-item label="时间类型" prop="dateType">
                        <el-select
                            v-model="formSearch.dateType"
                            filterable
                            placeholder="请选择"
                            style="width: 322px"
                            @keyup.enter.native="getList"
                        >
                            <el-option
                                v-for="item in optionsDateTypes"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            >
                            </el-option>
                        </el-select>
                    </el-form-item>
                </div>
            </div>
            <div class="search-wrap">
                <div class="search-item" :class="{left: !isMobile}">
                    <el-form-item label="时间区间" prop="startDate">
                        <el-date-picker
                            type="date"
                            placeholder="选择日期"
                            format="yyyy/MM/dd"
                            prefix-icon="false"
                            v-model="formSearch.startDate"
                            :clearable="true"
                            class="custom-the-datepicker"
                            style="width: 88px;margin-right: 5px;"
                            @change="onChangeDate($event, 'startDate')"
                            @keyup.enter.native="getList"
                        ></el-date-picker>
                        <el-time-select
                            prefix-icon="false"
                            placeholder="起始时间"
                            v-model="formSearch.startTime"
                            class="custom-the-datepicker"
                            style="width: 60px;"
                            :clearable="false"
                            :picker-options="{
                                start: '00:00',
                                step: '01:00',
                                end: '24:00'
                            }"
                            @change="onChangeDate($event, 'startTime')"
                            @keyup.enter.native="getList"
                        >
                        </el-time-select>
                        <span style="display: inline-block; padding: 0 5px;">-</span>
                        <el-date-picker
                            type="date"
                            placeholder="选择日期"
                            format="yyyy/MM/dd"
                            prefix-icon="false"
                            v-model="formSearch.endDate"
                            :clearable="true"
                            class="custom-the-datepicker"
                            style="width: 88px;margin-right: 5px;"
                            @change="onChangeDate($event, 'endDate')"
                            @keyup.enter.native="getList"
                        ></el-date-picker>
                        <el-time-select
                            prefix-icon="false"
                            placeholder="结束时间"
                            v-model="formSearch.endTime"
                            class="custom-the-datepicker"
                            style="width: 60px; margin-right: 5px;"
                            :clearable="false"
                            :picker-options="{
                                start: '00:00',
                                step: '01:00',
                                end: '24:00'
                            }"
                            @change="onChangeDate($event, 'endTime')"
                            @keyup.enter.native="getList"
                        >
                        </el-time-select>
                    </el-form-item>
                </div>
                <div class="search-item" :class="{left: !isMobile}">
                    <el-form-item label="时间快捷项" prop="selectMenu">
                        <el-select
                            style="width: 322px"
                            v-model="formSearch.selectMenu"
                            placeholder="请选择"
                            :popper-append-to-body="false"
                            clearable
                            @change="onChangeTimeRange"
                            @clear="onChangeTimeRange('All')"
                            @keyup.enter.native="getList"
                        >
                            <el-option
                                v-for="item in menuOptions"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            >
                            </el-option>
                        </el-select>
                    </el-form-item>
                </div>
            </div>

            <div class="search-wrap">
                <div class="search-item" :class="{left: !isMobile}">
                    <el-form-item label="  ">
                        <el-button type="primary" style="min-width: 120px;" @click="getList">查询</el-button>
                        <br v-if="isMobile" />
                        <el-button type="default" style="min-width: 120px;" @click="resetForm('formSearch')"
                            >重置</el-button
                        >
                    </el-form-item>
                </div>
            </div>
        </el-form>

        <div v-loading="isLoading" style="margin-top: 40px;">
            <el-table
                :data="tableData"
                border
                style="width: 100%;margin-bottom: 40px;"
                @selection-change="handleSelectionChange"
                ref="multipleUpdateTable"
                :summary-method="getSummaries"
                show-summary
            >
                <el-table-column type="selection" width="55"> </el-table-column>
                <el-table-column type="index"> </el-table-column>
                <el-table-column prop="title" label="项目列表（利润）">
                    <template v-slot="{row}">{{ row.title }}（{{ row.count }}）</template>
                </el-table-column>
                <el-table-column prop="total" label="本期金额（元）">
                    <template v-slot="{row}">{{ row.total | keep2decimalPlaces }}</template>
                </el-table-column>
            </el-table>
            <el-table
                :data="itemInList"
                border
                style="width: 100%;margin-bottom: 40px;"
                @selection-change="handleSelectionChange"
                ref="multipleUpdateTable"
                :summary-method="getSummaries"
                show-summary
            >
                <el-table-column type="selection" width="55"> </el-table-column>
                <el-table-column type="index"> </el-table-column>
                <el-table-column prop="itemOutIn.name" label="项目列表（收入类）">
                    <template v-slot="{row}">{{ row.itemOutIn.name }}（{{ row.count }}）</template>
                </el-table-column>
                <el-table-column prop="value" label="本期金额（元）">
                    <template v-slot="{row}">{{ row.value | keep2decimalPlaces }}</template>
                </el-table-column>
            </el-table>
            <el-table
                :data="itemOutListOther"
                border
                style="width: 100%;margin-bottom: 40px;"
                @selection-change="handleSelectionChange"
                ref="multipleUpdateTable"
                :summary-method="getSummaries"
                show-summary
            >
                <el-table-column type="selection" width="55"> </el-table-column>
                <el-table-column type="index"> </el-table-column>
                <el-table-column prop="itemOutIn.name" label="项目列表（支出类-成本及其他支出）">
                    <template v-slot="{row}">{{ row.itemOutIn.name }}（{{ row.count }}）</template>
                </el-table-column>
                <el-table-column prop="value" label="本期金额（元）">
                    <template v-slot="{row}">{{ row.value | keep2decimalPlaces }}</template>
                </el-table-column>
            </el-table>
            <el-table
                :data="itemOutListAssets"
                border
                style="width: 100%;margin-bottom: 40px;"
                @selection-change="handleSelectionChange"
                ref="multipleUpdateTable"
                :summary-method="getSummaries"
                show-summary
            >
                <el-table-column type="selection" width="55"> </el-table-column>
                <el-table-column type="index"> </el-table-column>
                <el-table-column prop="itemOutIn.name" label="项目列表（支出类-资产支出）">
                    <template v-slot="{row}">{{ row.itemOutIn.name }}（{{ row.count }}）</template>
                </el-table-column>
                <el-table-column prop="value" label="本期金额（元）">
                    <template v-slot="{row}">{{ row.value | keep2decimalPlaces }}</template>
                </el-table-column>
            </el-table>
        </div>
    </LayoutWrap>
</template>
<script>
import {mapGetters} from 'vuex';
import {getReportsProfits} from '@/api/report';
import {deepCopy} from '@/utils/utils';
import {v4 as uuidv4} from 'uuid';
import moment from 'moment';
import {getApiList as getDepots} from '@/api/depot';
export default {
    name: 'order',
    data() {
        return {
            srcList: [],
            uuidv4,
            formSearch: {
                startDate: '',
                startTime: '',
                endDate: '',
                endTime: '',

                selectMenu: 'All', // 'CustomTime' 'LastWeek',
                depot: '',

                numberType: 'money',
                numberStart: '',
                numberEnd: '',

                type: undefined, // 单据类型
                itemOutInId: undefined, // 收支项目

                dateType: 'date',
                keyName: 'abstract',
                keyValue: '',
                pageSize: 10,
                page: 1,
                count: 0
            },
            optionsTypes: [
                {label: '收入', value: '1'},
                {label: '支出', value: '2'},
                {label: '转账', value: '5'}
            ],
            keyOptions: [
                // {label: '提货日期', value: 'datetime', disabled: false},
                // {label: '店铺（间）', value: 'store', disabled: false},
                // {label: '每日单量', value: 'order', disabled: false},
                // {label: '仓库名称', value: 'depotInfo.name', disabled: false},
                {label: '摘要', value: 'abstract', disabled: false}
            ],
            isLoading: false,
            visibleDetail: false,
            multipleSelection: [],
            optionsDateTypes: [{label: '发生时间', value: 'date'}],
            optionsNumberTypes: [{label: '金额', value: 'money'}],
            optionsSortTypes: [
                {label: '时间顺序', value: 'PositiveOrder'},
                {label: '时间倒序', value: 'ReverseOrder'}
            ],
            optionsDepots: [],

            tableData: [], // 利润

            itemInList: [], // 收入类
            itemOutListOther: [], // 支出类-成本及其他支出
            itemOutListAssets: [], // 支出类-资产支出
            itemOutList: [], // 支出大类
            itemTransferList: []
        };
    },
    computed: {
        ...mapGetters({
            isMobile: 'app/isMobile'
        })
    },
    created() {
        const result = new Array(12).fill('').map((item, index) => {
            const month = (index + 1).toString();
            return {
                label: `${month}月份`,
                value: `${month}`,
                method: (month => () => {
                    month = month.padStart(2, '0');
                    const startDate = moment().format(`YYYY-${month}-01`);
                    const endDate = moment(startDate)
                        .endOf('month')
                        .format('YYYY-MM-DD');

                    this.formSearch = {
                        ...this.formSearch,
                        startDate: startDate,
                        startTime: '00:00',
                        endDate: endDate,
                        endTime: '24:00'
                    };
                })(month)
            };
        });

        this.menuOptions = [
            {
                label: '所有时间',
                value: 'All',
                method: () => {
                    this.formSearch = {
                        ...this.formSearch,
                        startDate: '',
                        startTime: '',
                        endDate: '',
                        endTime: ''
                    };
                }
            },
            {label: '自定义时间', value: 'CustomTime', method: () => {}},
            {
                label: '今天',
                value: 'Today',
                method: () => {
                    const startDate = moment().format('YYYY-MM-DD');
                    const endDate = startDate;

                    this.formSearch = {
                        ...this.formSearch,
                        startDate: startDate,
                        startTime: '00:00',
                        endDate: endDate,
                        endTime: '24:00'
                    };
                }
            },
            {
                label: '昨天',
                value: 'Yesterday',
                method: () => {
                    const startDate = moment()
                        .add(-1, 'days')
                        .format('YYYY-MM-DD');
                    const endDate = startDate;

                    this.formSearch = {
                        ...this.formSearch,
                        startDate: startDate,
                        startTime: '00:00',
                        endDate: endDate,
                        endTime: '24:00'
                    };
                }
            },
            {
                label: '最近一月',
                value: 'LastMonth',
                method: () => {
                    const startDate = moment()
                        .add(-30, 'days')
                        .format('YYYY-MM-DD');
                    const endDate = moment().format('YYYY-MM-DD');

                    this.formSearch = {
                        ...this.formSearch,
                        startDate: startDate,
                        startTime: '00:00',
                        endDate: endDate,
                        endTime: '24:00'
                    };
                }
            }
        ];
        this.menuOptions.push(...result);

        // const selectMenu = `${moment().format('MM') - 0}`;
        // this.formSearch.selectMenu = selectMenu;

        // const target = this.menuOptions.find(item => item.value === selectMenu);
        // target && target.method();

        this.getList();
        this.getAllOptions();
    },
    beforeDestroy() {},
    methods: {
        getAllOptions() {
            const newItem = {
                page: 1,
                pageSize: 1000
            };
            getDepots({...newItem, isDeleted: false})
                .then(({data: res}) => {
                    this.optionsDepots = res.data;
                    return res.data;
                })
                .catch(error => {
                    console.error('error', error);
                });
        },
        getSummaries(param) {
            const {columns, data} = param;
            const sums = [];
            columns.forEach((column, index) => {
                if (index === 0) {
                    sums[index] = '合计';
                    return;
                }
                const values = data.map(item => Number(item[column.property]));
                if (column.property === 'total' || column.property === 'value') {
                    sums[index] = values.reduce((prev, curr) => {
                        const value = Number(curr);
                        if (!isNaN(value)) {
                            return prev + curr;
                        } else {
                            return prev;
                        }
                    }, 0);
                    sums[index] = `¥ ${sums[index].toFixed(2)}`;
                } else {
                    // sums[index] = 'N/A';
                    sums[index] = '';
                }
            });

            return sums;
        },
        onChangeTimeRange(value) {
            const target = this.menuOptions.find(item => item.value === value);
            if (target && target.method) {
                target.method();
            }
        },
        onChangeDate(value, type) {
            this.formSearch.selectMenu = 'CustomTime';

            if (type === 'startDate' && !value) {
                this.formSearch = {...this.formSearch, startTime: ''};
            }
            if (type === 'startDate' && value && !this.formSearch.startTime) {
                this.formSearch = {...this.formSearch, startTime: '00:00'};
            }
            if (type === 'endDate' && !value) {
                this.formSearch = {...this.formSearch, endTime: ''};
            }
            if (type === 'endDate' && value && !this.formSearch.endTime) {
                this.formSearch = {...this.formSearch, endTime: '24:00'};
            }
        },
        resetForm() {
            const formSearch = this.$options.data().formSearch;

            this.formSearch = {
                ...this.formSearch,
                ...formSearch
            };
        },
        handleSelectionChange(value) {
            this.multipleSelection = deepCopy(value).map(item => {
                item.uuid = uuidv4();
                return item;
            });
        },

        // 获取列表数据
        getList() {
            this.isLoading = true;
            const formSearch = this.formSearch;
            const newItem = {
                depot: formSearch.depot || undefined,
                remark: formSearch.remark || undefined,
                type: formSearch.type || undefined,
                itemOutInId: formSearch.itemOutInId || undefined,
                sort: formSearch.sortType === 'ReverseOrder' ? `-${formSearch.dateType}` : formSearch.dateType
            };

            const dateType = formSearch.dateType;
            if (dateType && (formSearch.startDate || formSearch.endDate)) {
                newItem[dateType] = {};

                if (formSearch.startDate) {
                    newItem[dateType].gte = new Date(
                        `${moment(formSearch.startDate).format('YYYY-MM-DD')} ${formSearch.startTime}`
                    ).getTime();
                }
                if (formSearch.endDate) {
                    newItem[dateType].lt = new Date(
                        `${moment(formSearch.endDate).format('YYYY-MM-DD')} ${formSearch.endTime}`
                    ).getTime();
                }
            }
            const numberType = formSearch.numberType;

            if (numberType && (formSearch.numberStart || formSearch.numberEnd)) {
                newItem[numberType] = {};

                if (formSearch.numberStart) {
                    newItem[numberType].gte = formSearch.numberStart - 0;
                }
                if (formSearch.numberEnd) {
                    newItem[numberType].lte = formSearch.numberEnd - 0;
                }
            }

            if (formSearch.keyValue) {
                newItem[formSearch.keyName] = formSearch.keyValue;
            }
            getReportsProfits(newItem)
                .then(({data: res}) => {
                    if (res.status === 200) {
                        const {data, count, page, pageSize} = res;

                        const {itemInList, itemOutList, itemTransferList} = data.reduce(
                            (total, item) => {
                                if (item.itemOutIn && item.itemOutIn.type === '1') {
                                    total.itemInList.push(item);
                                } else if (item.itemOutIn && item.itemOutIn.type === '2') {
                                    total.itemOutList.push(item);
                                } else {
                                    total.itemTransferList.push(item);
                                }
                                return total;
                            },
                            {itemInList: [], itemOutList: [], itemTransferList: []}
                        );

                        this.itemInList = itemInList;
                        this.itemOutList = itemOutList;
                        this.itemOutListOther = itemOutList.filter(item => !item.itemOutIn.name.includes('支出-资产'));
                        this.itemOutListAssets = itemOutList.filter(item => item.itemOutIn.name.includes('支出-资产'));
                        this.itemTransferList = itemTransferList;

                        this.tableData = [
                            {
                                title: '收入类合计',
                                count: itemInList.reduce((total, acc) => acc.count + total, 0),
                                total: itemInList.reduce((total, acc) => acc.value + total, 0)
                            },
                            {
                                title: '支出类-成本及其他支出合计',
                                count: this.itemOutListOther.reduce((total, acc) => acc.count + total, 0),
                                total: this.itemOutListOther.reduce((total, acc) => acc.value + total, 0) * -1
                            },
                            {
                                title: '支出类-资产支出合计',
                                count: this.itemOutListAssets.reduce((total, acc) => acc.count + total, 0),
                                total: this.itemOutListAssets.reduce((total, acc) => acc.value + total, 0) * -1
                            }
                        ];
                        this.formSearch = {...this.formSearch, page, pageSize, count};
                    }
                })
                .catch(error => {
                    console.log(error);
                    const data = error.response && error.response.data;
                    if (data && data.error) {
                        this.$message({showClose: true, type: 'error', message: data.error});
                    } else {
                        this.$message({showClose: true, type: 'error', message: '获取数据失败'});
                    }
                })
                .finally(() => (this.isLoading = false));
        }
    }
};
</script>

<style lang="scss" scoped>
::v-deep {
    .cell {
        padding-left: 5px;
        padding-right: 5px;
    }
    .image-column-wrapper {
        .cell {
            padding-left: 5px;
            padding-right: 5px;
        }
    }
    .upload-length--1 {
        .el-upload {
            display: none;
        }
        .el-upload-list__item:first-child {
            margin-top: 0;
        }
    }
    .el-upload-dragger {
        width: auto;
        height: auto;
    }
}
.custom-the-datepicker,
.custom-the-select_time,
.custom-the-select_key {
    ::v-deep {
        .el-input__inner {
            padding-left: 10px;
            padding-right: 10px;
        }
    }
}
</style>
